package com.heima.kafka.sample;


import org.apache.kafka.clients.producer.*;

import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.kafka的配置
        Properties properties = new Properties();
        //kafka的远程连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"47.97.188.241:9092");
        //发送失败,重试的次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        //消息的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //确认机制
        properties.put(ProducerConfig.ACKS_CONFIG,"all");
        //数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"lz4");
        //2.生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<>(properties);
        //封装发送的消息
        ProducerRecord<String,String> record = new ProducerRecord<>("itcast-topic-input","kafka","hello kafka hello itcast");

        /*//3.同步发送消息
        RecordMetadata recordMetadata = producer.send(record).get();
        System.out.println(recordMetadata.offset());*/
        //异步发送消息
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (e != null) System.out.println("记录异常信息到记录表中");
                System.out.println(recordMetadata.offset());
            }
        });

        //4.关闭消息通道,必须关闭才能发送消息成功
        producer.close();
    }
}
